<template>
  <div>
    <div>
      <div class="top-operate">
        <div class="top-operate-default flex-col pad-t-20 pad-b-5 mar-b-14" style="align-items: baseline; height: 100%; overflow: visible">
          <!-- 顶部搜索 -->
          <div class="search-item">
            <label>订单搜索：</label>
            <el-select v-model="textCol" class="width-120">
              <el-option label="订单号" value="orderNo"></el-option>
              <el-option label="平台订单号" value="externalOrderNo"></el-option>
              <el-option label="收货人" value="postReceiver"></el-option>
              <el-option label="收货人电话" value="postTel"></el-option>
              <el-option label="商品名称" value="goodsTitle"></el-option>
              <el-option label="商品货号" value="goodsCode"></el-option>
              <el-option label="sku外部编码" value="skuExternalCode"></el-option>
            </el-select>
            <el-input v-model.trim="textValue" placeholder="请输入内容" class="search-input-6"></el-input>
            <el-button class="mar-l-15 mar-r-16" type="text" @click="configFormVisible=true">同步设置</el-button>
          </div>
          <div class="toggle-bar" :class="searchToggle ? 'show-toggle' : 'hide-toggle'">
            <div class="search-item">
              <label>订单时间：</label>
              <el-select v-model="timeCol" class="width-120">
                <el-option label="创建时间" value="thirdPlatformCreateTime"></el-option>
                <el-option label="付款时间" value="payTime"></el-option>
                <el-option label="同步时间" value="syncTime"></el-option>
              </el-select>
              <el-date-picker v-model="timeValue"
                type="datetimerange"
                class="search-input-5"
                range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
            <div class="search-item">
              <label>平台类型：</label>
              <el-select v-model="defaultQuery.platformType" placeholder="请选择平台" clearable @change="doChangePlatformType" class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <template v-for="(val, key) in dict.platformType">
                  <el-option v-if="key != 99" :key="key" :label="val" :value="key"></el-option>
                </template>
              </el-select>
              <label class="mar-l-24">平台店铺：</label>
              <el-select v-model="defaultQuery.shopId" placeholder="请选择平台类型" clearable :disabled="!defaultQuery.platformType" class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="(item, index) in shopList" :key="index" :label="item.shopName" :value="item.shopId"></el-option>
              </el-select>
              <label class="mar-l-24">商品来源：</label>
              <el-select v-model="supplierType" clearable filterable class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <el-option label="总部自营" value="0"></el-option>
                <el-option label="淘宝联盟" value="2"></el-option>
                <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName" :value="item.supplierId"></el-option>
              </el-select>
            </div>
            <div class="search-item">
              <label>支付类型：</label>
              <el-select v-model="defaultQuery.payType" placeholder="支付类型" clearable class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="(val, key) in dict.payType" :key="key" :label="val" :value="key"></el-option>
              </el-select>
              <label class="mar-l-24">买家留言：</label>
              <el-select v-model="defaultQuery.buyerWordsFlag" placeholder="买家留言" clearable class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <el-option label="有内容" value="1"></el-option>
                <el-option label="无内容" value="0"></el-option>
              </el-select>
              <label class="mar-l-24">卖家备注：</label>
              <el-select v-model="defaultQuery.sellerWordsFlag" placeholder="卖家备注" clearable class="search-input-3">
                <el-option label="全部" value=""></el-option>
                <el-option label="有内容" value="1"></el-option>
                <el-option label="无内容" value="0"></el-option>
              </el-select>
            </div>
          </div>
          <div class="search-item">
            <label>订单状态：</label>
            <el-select v-model="defaultQuery.orderStatus" placeholder="订单状态" clearable class="search-input-3">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(val, key) in dict.orderStatus" :key="key" :label="val" :value="key"></el-option>
            </el-select>
            <label class="mar-l-24">售后状态：</label>
            <el-select v-model="defaultQuery.afterSaleFlag" placeholder="售后状态" clearable class="search-input-3">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(val, key) in dict.afterSaleFlag" :key="key" :label="val" :value="key"></el-option>
            </el-select>
            <label class="mar-l-24">订单异常类型：</label>
            <el-select v-model="defaultQuery.exceptionType" placeholder="异常类型" clearable class="search-input-4">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(val, key) in dict.exceptionType" :key="key" :label="val" :value="key"></el-option>
            </el-select>
            <label class="mar-l-24">同步状态：</label>
            <el-select v-model="defaultQuery.syncStatus" placeholder="同步状态" clearable class="search-input-3">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(val, key) in dict.syncStatus" :key="key" :label="val" :value="key"></el-option>
            </el-select>
          </div>
          <div class="search-item">
            <label class="width-50"></label>
            <el-button-group class="mar-l-20 search-btn-g">
              <el-button type="primary" @click="doSearch">查询</el-button>
              <el-button plain @click="doResetSearch">重置</el-button>
            </el-button-group>
            <div class="cursor-p mar-l-24" @click="toggleShow">
              <span>{{ searchToggle ? '收起' : '更多筛选条件' }}</span>
              <i class="font-color-6" :class="searchToggle ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            </div>
          </div>
        </div>
        <div class="font-14 v-align-c">
          <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span class="mar-l-9">当页全选</span></el-checkbox>
          <span class="pad-l-4 pad-r-4">|</span>
          <div class="width-80">已选{{multipleSelection.length}}项</div>
          <el-button class="mar-l--2 mar-r-5 search-btn-1" @click="doExport">导出</el-button>
          <el-button class="mar-l--2 mar-r-5 search-btn-1" @click="doBatchReSync">批量重新同步</el-button>
          <el-button class="mar-l-15 mar-r-20 search-btn-1" @click="doBatchGenerate">批量生成订单</el-button>
          <el-checkbox v-model="syncForm.buyerWordsFlag" true-label="1" false-label="0">有买家留言不生成</el-checkbox>
          <el-checkbox class="mar-l--10" v-model="syncForm.sellerWordsFlag" true-label="1" false-label="0">有卖家备注不生成</el-checkbox>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column width="45px" type="selection"></el-table-column>
          <el-table-column width="265px" label="基本信息" fixed="left" prop="externalOrderNo">
            <template slot-scope="scope">
              <div class="v-align-c">
                <img class="width-16 height-16" :src="constant.platformIconObj[scope.row.platformType]"/>
                <span class="mar-l-6">{{scope.row.externalOrderNo}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="125px" label="同步状态">
            <template slot-scope="scope">
              <span class="font-color">{{ dict.syncStatus[scope.row.syncStatus] }}</span>
            </template>
          </el-table-column>
          <el-table-column width="220px" label="时间">
            <template slot-scope="scope">
              <div>创建：<span class="font-color">{{ scope.row.thirdPlatformCreateTime }}</span></div>
              <div>支付：<span class="font-color">{{ scope.row.payTime }}</span></div>
              <div>同步：<span class="font-color">{{ scope.row.syncTime }}</span></div>
            </template>
          </el-table-column>
          <el-table-column width="130px" label="是否异常">
            <template slot-scope="scope">
              <div>
                <span :class="scope.row.exceptionTypeList.length == 0 ? 'font-blue' : 'font-red'">
                  {{scope.row.exceptionTypeList.length > 0 ? dict.exceptionType[scope.row.exceptionTypeList[0]] : '无异常'}}
                </span>
                <el-tooltip placement="top" effect="light" v-if="scope.row.exceptionTypeList.length > 1">
                  <template v-for="(item,i) in scope.row.exceptionTypeList">
                    <div slot="content" :key="i">{{dict.exceptionType[item]}}<br/></div>
                  </template>
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="190px" label="收货人">
            <template slot-scope="scope">
              <div><span class="font-color">{{ scope.row.customerName }}</span></div>
              <div><span class="font-color">{{ scope.row.customerPhone }}</span></div>
              <div class="font-color flex-item line-2 mar-t-2" :title="scope.row.consigneeDetailAddress">{{ scope.row.consigneeDetailAddress }}</div>
              <div>
                <template v-if="scope.row.changeReceiverStatus == 10">
                  <span class="font-red">顾客已申请修改</span>
                  <br/>
                  <span class="font-blue cursor-p" @click="doAuditReceiveAddress(scope.row)">点击审核</span>
                </template>
                <template v-if="scope.row.changeReceiverStatus == 20">
                  <span class="font-red">顾客已申请修改</span>
                  <br/>
                  <span class="font-blue">已审核</span>
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="130px" label="买家信息">
            <template slot-scope="scope">
              <div>昵称：<span class="font-color">{{ scope.row.buyerNick ? scope.row.buyerNick : '--' }}</span></div>
              <div class="flex">
                <div>留言：</div>
                <div class="font-color flex-item line-2 mar-t-2">{{ scope.row.buyerWords ? scope.row.buyerWords : '--' }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="130px" label="卖家备注">
            <template slot-scope="scope">
              <span class="line-2" :title="scope.row.sellerWords">{{ scope.row.sellerWords ? scope.row.sellerWords : '--'  }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px" label="成交信息">
            <template slot-scope="scope">
              <div>商品数量：<span class="font-color">{{scope.row.goodsNum}}</span></div>
              <div>订单金额：<span class="font-color-ff9">￥{{scope.row.orderAmount}}</span></div>
            </template>
          </el-table-column>
          <el-table-column width="160px" label=" 订单/售后/支付">
            <template slot-scope="scope">
              <div>订单状态：<span class="font-blue">{{dict.orderStatus[scope.row.orderStatus]}}</span></div>
              <div>售后状态：<span :class="scope.row.afterSaleFlag == 0 ? 'font-color' : 'font-red'">{{dict.afterSaleFlag[scope.row.afterSaleFlag]}}</span></div>
              <div>支付类型：<span class="font-color">{{dict.payType[scope.row.payType] || '（未知）'}}</span></div>
            </template>
          </el-table-column>
          <el-table-column width="80px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" v-if="scope.row.generateFlag == 1" @click="doGenerate(scope.row)">生成</el-button>
              <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看</el-button>
              <el-button type="text" size="medium" v-if="scope.row.syncStatus != 0" @click="doReSync(scope.row)">{{ scope.row.mergeType == 1 ? '重新同步' : '删除' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]" 
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
      
    <!-- 同步设置dialog -->
    <el-dialog width="600px" title="同步设置" v-el-drag-dialog :visible.sync="configFormVisible">
      <third-order-config :showFlag="configFormVisible" @callback="doCallbackConfig"></third-order-config>
    </el-dialog>

    <!-- 审核收货信息dialog -->
    <el-dialog width="670px" title="审核收货信息" v-el-drag-dialog :visible.sync="auditReceiveVisible">
      <third-order-audit-receive :showFlag="auditReceiveVisible" :thirdOrderId="selectId" @callback="doCallbackAuditReceive"></third-order-audit-receive>
    </el-dialog>
  </div>
</template>

<script>
  import { pageThirdOrder, deleteThirdOrder, doGenerateOrder } from '@/api/goods/thirdOrder'
  import { downloadFile } from '@/api/common/common'
  import { listThirdShop } from '@/api/user/third-shop'
  import { listSupplier } from '@/api/user/supplier'
  import elDragDialog from '@/directive/el-dragDialog'
  import thirdAuth from '@/views/shop/components/third-auth'
  import thirdOrderConfig from '@/views/goods/order/components/third-order-config'
  import thirdOrderAuditReceive from '@/views/goods/order/components/third-order-audit-receive'

  export default {
    mixins: [thirdAuth],
    components: { thirdOrderConfig, thirdOrderAuditReceive },
    directives: {
      elDragDialog
    },
    data() {
      return {
        // 文本model
        textCol: 'externalOrderNo',
        textValue: '',
        // 时间model
        timeCol: 'thirdPlatformCreateTime',
        timeValue: [],
        // 商品来源
        supplierType: '',
        // 默认查询表单
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          memberId: '',
          shopType: 1,
          syncStatus: '',
          platformType: '',
          shopId: '',
          buyerWordsFlag: '',
          sellerWordsFlag: '',
          orderStatus: '',
          payType: '',
          exceptionType: ''
        },
        // 查询表单
        searchListQuery: {},
        // 数据字典
        dict: {
          orderStatus: {},
          syncStatus: {},
          platformType: {},
          payType: {},
          exceptionType: {}
        },
        // 同步表单
        syncForm: {
          buyerWordsFlag: '0',
          sellerWordsFlag: '0'
        },
        // 选中第三方订单id
        selectId: '',
        // 同步设置visible
        configFormVisible: false,
        // 审核收货信息visible
        auditReceiveVisible: false,
        // 店铺集合
        shopList: [],
        syncShopList: [],
        // 供应商集合
        supplierList: [],
        total: 0,
        listLoading: false,
        dataList: [],
        multipleSelection: [],
        searchToggle: false,
        allChecked: false
      }
    },
    // 初始化页面
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      listSupplier({ enterpriseId: this.getEnterpriseId() }).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      this.initList()
    },
    methods: {
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
          this.dataList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      toggleShow() {
        this.searchToggle = !this.searchToggle
      },
      // 初始化
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        pageThirdOrder(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
        })
      },
      // 设置查询条件
      setSearchListQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.timeCol
        this.searchListQuery.startDate = (this.timeValue && this.timeValue.length > 0) ? this.timeValue[0] : ''
        this.searchListQuery.endDate = (this.timeValue && this.timeValue.length > 1) ? this.timeValue[1] : ''
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.memberId = this.getMemberId()
        if (this.supplierType === '0' || this.supplierType === '2') {
          this.searchListQuery.goodsSource = this.supplierType
        } else {
          this.searchListQuery.supplierId = this.supplierType
        }
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.timeCol = originData.timeCol
        this.timeValue = originData.timeValue
        this.supplierType = originData.supplierType
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 条件部 平台类型切换事件
      doChangePlatformType() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.defaultQuery.platformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          this.shopList = response.data
          this.defaultQuery.shopId = ''
        })
      },
      // 同步设置回调事件
      doCallbackConfig() {
        this.configFormVisible = false
      },
      // 批量生成订单事件
      doBatchGenerate() {
        if (this.multipleSelection.length === 0) {
          this.$message({ message: '请勾选订单', type: 'error' })
          return
        }
        const params = {
          enterpriseId: this.getEnterpriseId(),
          buyerWordsFlag: this.syncForm.buyerWordsFlag,
          sellerWordsFlag: this.syncForm.sellerWordsFlag,
          thirdOrderIds: this.multipleSelection.map(item => item.thirdOrderId)
        }
        this.$bus.$emit('asyncHandle', '300001', params, () => {
          this.$emit('updateOrderStat')
          this.initList()
        })
      },
      // 生成订单事件
      doGenerate(row) {
        this.listLoading = true
        doGenerateOrder({
          externalOrderNo: row.externalOrderNo,
          shopId: row.shopId,
          platformType: row.platformType
        }).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({ message: '生成成功', type: 'success' })
          this.$emit('updateOrderStat')
          this.initList()
        })
      },
      // 地址审核事件
      doAuditReceiveAddress(row) {
        this.selectId = row.thirdOrderId
        this.auditReceiveVisible = true
      },
      // 审核地址回调事件
      doCallbackAuditReceive(callbackFlag) {
        if (callbackFlag) {
          this.initList()
        }
        this.auditReceiveVisible = false
      },
      // 查看详情事件
      doLinkDetail(row) {
        const routeData = this.$router.resolve({
          path: '/order/third-order/detail',
          query: { thirdOrderId: row.thirdOrderId }
        })
        window.open(routeData.href, '_blank')
      },
      // 导出事件
      doExport() {
        const url = '/order/third/exportOrder'
        const fileName = '平台订单_' + new Date().toLocaleString() + '.xlsx'
        if (this.multipleSelection.length > 0) {
          const thirdOrderIds = this.multipleSelection.map(item => item.thirdOrderId)
          downloadFile(url, { thirdOrderIds: thirdOrderIds }, fileName)
        } else {
          this.setSearchListQuery()
          downloadFile(url, this.searchListQuery, fileName)
        }
      },
      // 重新同步事件
      doReSync(row) {
        this.$confirm('确定重新同步订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          var form = {
            thirdOrderId: row.thirdOrderId
          }
          deleteThirdOrder(form).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.$message({ message: '操作成功', type: 'success' })
            this.$emit('updateOrderStat')
            this.initList()
          })
        }).catch(() => {
        })
      },
      // 批量重新同步事件
      doBatchReSync() {
        if (this.multipleSelection.length === 0) {
          this.$message({ message: '请勾选数据', type: 'warning' })
          return
        }
        this.$confirm('确定重新同步订单？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const params = {
            thirdOrderIds: this.multipleSelection.map(item => item.thirdOrderId)
          }
          this.$bus.$emit('asyncHandle', '300006', params, () => {
            this.$message({ message: '操作成功', type: 'success' })
            this.$emit('updateOrderStat')
            this.initList()
          })
        }).catch(() => {
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.dataList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
/deep/ .search-input-2{
  &.el-input__inner{
    width: 438px;
  }
}
/deep/ .search-input-5{
  &.el-input__inner{
    width: 400px;
  }
}
/deep/ .search-input-1{
  .el-input{
    width: 170px;
  }
}
/deep/ .search-input-3{
  .el-input{
    width: 150px;
  }
}
/deep/ .search-input-4{
  .el-input{
    width: 122px;
  }
}
/deep/ .search-input-6{
  &.el-input{
    width: 400px;
  }
}
/deep/ .search-resbtn{
  &.el-button{
    padding: 10px 31px;
  }
}
/deep/ .search-btn-g{
  .el-button{
    padding: 10px 23px;
    &:last-child{
      margin-left: -1px;
    }
  }
}
/deep/ .search-btn-1{
  &.el-button{
    padding: 9px 16px;
  }
}
.toggle-bar{
  transition: 0.5s;
  overflow: hidden;
}
.show-toggle{
  height: 135px;
}
.hide-toggle{
  height: 0px;
}
// 2行文字展示
.line-2{
  line-height: 1.4;
  overflow:hidden;
  text-overflow:ellipsis;
  display:-webkit-box;
  -webkit-line-clamp:2;
  /* autoprefixer: ignore next */
  -webkit-box-orient:vertical;
  word-break:break-word;
}
.font-color-ff9{
  color: #ff9f00;
}
</style>
